package com.zhixi100.gatewayservice.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhixi100.framework.common.ObjectRestResponse;
import com.zhixi100.framework.utils.RestResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import static org.bouncycastle.crypto.tls.CipherType.stream;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

    /**
     * 过滤器类型，前置过滤器
     *
     * @return
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 过滤器顺序，越小越先执行
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 3;
    }

    /**
     * 过滤器是否生效
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        //TODO 后期接口列表保存到 数据库 或 redis 中
        //不需要登录的接口
        String uri = request.getRequestURI();
        if ("/api/u/v1/login".equalsIgnoreCase(uri)) {
            return false;
        } else if ("/api/u/v1/logout".equalsIgnoreCase(uri)) {
            return false;
        }

        return true;
    }

    /**
     * 业务逻辑
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        //未登录不让访问
        if (user == null) {
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            context.setResponseBody(getErrorRes(String.valueOf(HttpStatus.UNAUTHORIZED.value()), "未登录"));
        }

        return null;
    }

    private String getErrorRes(String status, String mes) {
        Map map = new HashMap();
        map.put("status", status);
        map.put("message", mes);
        map.put("rel", false);

        String str = "{\"rel\":false,\"message\":\"it is not login\",\"status\":\"401\"}";
        String body = null;
        try {
            body = new String(str.getBytes(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("getErrorRes::异常");
        }
        return body;
    }
}
